import { Injectable } from '@nestjs/common';
// import { OrderEditDto, TokenInfo } from './order.dto'
import { OrderDto } from './order.dto';
import * as db from '../../../entity'
// import { Between } from 'typeorm';
import * as dateFns from 'date-fns'
import { serverCode } from '../../../tool/server.code'

@Injectable()
export class ManagerOrderService {
    // constructor(private readonly) { }

    async getList(order: OrderDto) {
        if (order.token) {
            const findToken = await db.UserToken.findOne({
                where: {
                    token: order.token,
                    status: db.UserTokenStatusEnum.ENABLE,
                    type: db.UserTokenTypeEnum.CREDITER,
                }
            })
            if (!findToken) {
                return { msg: '访问令牌不存在', code: serverCode.LOGINAUTHFAIL }
            }
            if (dateFns.isAfter(new Date(), findToken.expire_time)) {
                findToken.status = db.SmsCodeStatusEnum.DISABLE;
                findToken.save();
                return { msg: '访问令牌已经过期，请重新获取', code: serverCode.LOGINAUTHFAIL }
            }
            findToken.expire_time = dateFns.addDays(new Date(), 7);
            await findToken.save();
        }
        const pageIndex = order.data.pageIndex ? order.data.pageIndex : 1;
        const lists = await db.Order.find({
            where: `status in (${db.OrderStatusEnum.NORMAL},${db.OrderStatusEnum.PAID})`,
            order: {
                order_id: "DESC"
            },
            skip: (pageIndex - 1) * 10,
            take: 10,
        })
        const list = await Promise.all(lists.map(async it => {
            return {
                id: it.order_id,
                name: it.name,
                city: it.city,
                lendLimit: it.lend,
                lendTime: it.time_limit,
                purpose: it.purpose,
                worth: it.worth,
                income: it.income,
                incomeType: it.income_type,
                socialInsurance: it.social_insurance,
                accumulationFund: it.accumulation_fund,
                workYear: it.work_year,
                house: it.house,
                car: it.car,
                status: it.status,
                createTime: dateFns.format(it.create_time, 'YYYY-MM-DD HH:mm:ss')
            }
        }))
        const count = await db.Order.count({
            where: `status in (${db.OrderStatusEnum.NORMAL},${db.OrderStatusEnum.PAID})`,
        })
        const totalPage = Math.ceil(count / 10);
        return { data: { list, totalPage } }
    }

    async orderDetail(order) {
        let findToken;
        if (order.token) {
            findToken = await db.UserToken.findOne({
                where: {
                    token: order.token,
                    status: db.UserTokenStatusEnum.ENABLE,
                    type: db.UserTokenTypeEnum.CREDITER,
                }
            })
            if (!findToken) {
                return { msg: '访问令牌不存在', code: serverCode.LOGINAUTHFAIL }
            }
            if (dateFns.isAfter(new Date(), findToken.expire_time)) {
                findToken.status = db.SmsCodeStatusEnum.DISABLE;
                findToken.save();
                return { msg: '访问令牌已经过期，请重新获取', code: serverCode.LOGINAUTHFAIL }
            }
            findToken.expire_time = dateFns.addDays(new Date(), 7);
            await findToken.save();
        }

        const findOrder = await db.Order.findOne({
            where: {
                order_id: order.data.id
            }
        })
        if (!findOrder) {
            return { msg: '订单不存在', code: serverCode.ERROR }
        }
        const findUserOrder = findToken ? await db.UserBuyRecords.findOne({
            where: {
                user_id: findToken.user_id,
                order_id: findOrder.order_id
            }
        }) : null;
        const info = {
            id: findOrder.order_id,
            name: findOrder.name,
            city: findOrder.city,
            lendLimit: findOrder.lend,
            lendTime: findOrder.time_limit,
            purpose: findOrder.purpose,
            worth: findOrder.worth,
            income: findOrder.income,
            incomeType: findOrder.income_type,
            socialInsurance: findOrder.social_insurance,
            accumulationFund: findOrder.accumulation_fund,
            workYear: findOrder.work_year,
            house: findOrder.house,
            car: findOrder.car,
            status: findUserOrder ? db.OrderStatusEnum.SELFPAID : findOrder.status,
            createTime: dateFns.format(findOrder.create_time, 'YYYY-MM-DD HH:mm:ss'),
            mobile: findUserOrder ? findOrder.mobile : findOrder.mobile.replace(/^(\d{3})\d*(\d{4})$/, '$1****$2'),
        }
        return { data: { info: info } }
    }

    async orderBuy(order) {
        const findToken = await db.UserToken.findOne({
            where: {
                token: order.token,
                status: db.UserTokenStatusEnum.ENABLE,
                type: db.UserTokenTypeEnum.CREDITER,
            }
        })
        if (!findToken) {
            return { msg: '访问令牌不存在', code: serverCode.LOGINAUTHFAIL }
        }
        if (dateFns.isAfter(new Date(), findToken.expire_time)) {
            findToken.status = db.SmsCodeStatusEnum.DISABLE;
            findToken.save();
            return { msg: '访问令牌已经过期，请重新获取', code: serverCode.LOGINAUTHFAIL }
        }
        findToken.expire_time = dateFns.addDays(new Date(), 7);
        await findToken.save();

        const userAccount = await db.CrediterAccount.findOne({
            where: {
                crediter_id: findToken.user_id
            }
        })
        if (!userAccount) {
            return { msg: '账号异常，请联系管理员', code: serverCode.ERROR }
        }

        const findOrder = await db.Order.findOne({
            where: {
                order_id: order.data.id
            }
        })
        if (!findOrder) {
            return { msg: '订单不存在', code: serverCode.ERROR }
        }
        const findUserOrder = await db.UserBuyRecords.findOne({
            where: {
                user_id: findToken.user_id,
                order_id: findOrder.order_id
            }
        })
        if (findUserOrder) {
            return { msg: '该订单您已经购买了', code: serverCode.ERROR }
        }

        if (Number(userAccount.coin) < Number(findOrder.worth)) {
            return { msg: `金额不足，当前剩余${userAccount.coin}元`, code: serverCode.ERROR }
        }
        userAccount.coin = Number(userAccount.coin) - Number(findOrder.worth);
        await userAccount.save();
        const record = await db.UserBuyRecords.create({
            user_id: userAccount.crediter_id,
            order_id: findOrder.order_id,
            pay_number: findOrder.worth
        })
        await record.save();
        findOrder.status = db.OrderStatusEnum.PAID;
        await findOrder.save();
        return { data: { coin: userAccount.coin } }
    }

    async orderMyList(order) {
        const findToken = await db.UserToken.findOne({
            where: {
                token: order.token,
                status: db.UserTokenStatusEnum.ENABLE,
                type: db.UserTokenTypeEnum.CREDITER,
            }
        })
        if (!findToken) {
            return { msg: '访问令牌不存在', code: serverCode.LOGINAUTHFAIL }
        }
        if (dateFns.isAfter(new Date(), findToken.expire_time)) {
            findToken.status = db.SmsCodeStatusEnum.DISABLE;
            findToken.save();
            return { msg: '访问令牌已经过期，请重新获取', code: serverCode.LOGINAUTHFAIL }
        }
        findToken.expire_time = dateFns.addDays(new Date(), 7);
        await findToken.save();

        const userAccount = await db.CrediterAccount.findOne({
            where: {
                crediter_id: findToken.user_id
            }
        })
        if (!userAccount) {
            return { msg: '账号异常，请联系管理员', code: serverCode.ERROR }
        }
        const pageIndex = order.data.pageIndex ? order.data.pageIndex : 1;
        const lists = await db.UserBuyRecords.find({
            where: {
                user_id: userAccount.crediter_id
            },
            order: {
                order_id: "DESC"
            },
            skip: (pageIndex - 1) * 10,
            take: 10,
        })

        const list = await Promise.all(lists.map(async it => {
            const orderInfo = await db.Order.findOne({
                where: {
                    order_id: it.order_id,
                }
            })
            return {
                id: orderInfo.order_id,
                name: orderInfo.name,
                city: orderInfo.city,
                lendLimit: orderInfo.lend,
                lendTime: orderInfo.time_limit,
                purpose: orderInfo.purpose,
                worth: orderInfo.worth,
                income: orderInfo.income,
                incomeType: orderInfo.income_type,
                socialInsurance: orderInfo.social_insurance,
                accumulationFund: orderInfo.accumulation_fund,
                workYear: orderInfo.work_year,
                house: orderInfo.house,
                car: orderInfo.car,
                status: orderInfo.status,
                createTime: dateFns.format(orderInfo.create_time, 'YYYY-MM-DD HH:mm:ss')
            }
        }))
        const count = await db.UserBuyRecords.count({
            where: {
                user_id: userAccount.crediter_id
            },
        })
        const totalPage = Math.ceil(count / 10);
        return { data: { list, totalPage } }
    }
}